﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace OrBitDataModule.Adaptor
{

    public class CSendParam
    {
        private SendParamFormat _Format;
        private SendParamMode _Mode;
        private int _DelayTime;
        private readonly string _Data;
        private readonly byte[] _DataBytes = null;

        public CSendParam(SendParamFormat format, SendParamMode mode, int delayTime, byte[] data, int startIndex, int count)
        {
            _Format = format;
            _Mode = mode;
            _DelayTime = delayTime;
            _Data = string.Empty;
            if (data != null)
            {
                _DataBytes = new byte[count];
                Array.Copy(data, startIndex, _DataBytes, 0, count);

                if (Format == SendParamFormat.Hex)
                {
                    _Data = StreamConverter.ArrayToHexString(data, startIndex, count);
                }
                else
                {
                    _Data = StreamConverter.ArrayToAsciiString(Global.Encode, _DataBytes, startIndex, count);
                }
            }
        }

        public CSendParam(SendParamFormat format, SendParamMode mode, int delayTime, string data)
        {
            _Format = format;
            _Mode = mode;
            _DelayTime = delayTime;
            _Data = data;

            switch (_Format)
            {
                case SendParamFormat.ASCII:
                    _DataBytes = StreamConverter.AsciiStringToArray(Global.Encode, data);
                    break;
                case SendParamFormat.Hex:
                    _DataBytes = StreamConverter.HexStringToArray(data);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 十六进制字符串转十进制。
        /// </summary>
        /// <param name="hexStr"></param>
        /// <returns></returns>
        byte HexStringToByte(string hexStr)
        {
            return Convert.ToByte(hexStr, 16);
        }

        public SendParamFormat Format
        {
            get { return _Format; }
            set { _Format = value; }
        }

        public SendParamMode Mode
        {
            get { return _Mode; }
            set { _Mode = value; }
        }

        public int DelayTime
        {
            get { return _DelayTime; }
            set { _DelayTime = value; }
        }

        public int DataLen
        {
            get
            {
                if (_DataBytes != null)
                {
                    return _DataBytes.Length;
                }
                else
                {
                    return 0;
                }
            }
        }

        public string Data
        {
            get { return _Data; }
        }

        public string HexString
        {
            get
            {
                return StreamConverter.ArrayToHexString(_DataBytes);
            }
        }

        public string ASCIIString
        {
            get
            {
                return StreamConverter.ArrayToAsciiString(Global.Encode, _DataBytes);
            }
        }

        public string DecString
        {
            get
            {
                return StreamConverter.ArrayToDecimalString(_DataBytes);
            }

        }

        public byte[] DataBytes
        {
            get
            {
                return _DataBytes;
            }
        }


        public string ParameterString
        {
            get
            {
                return string.Format("{0}:{1}:{2}", (int)_Format, (int)_Mode, _DelayTime);
            }
        }
    }


    public enum SendParamFormat : int
    {
        ASCII = 0,
        Hex = 1
    }

    public enum SendParamMode : int
    {
        //SendDelayTime = 0,// 启动后延时发送
        SendAfterLastSend = 0,//上帧发送完成后
        SendAfterReceived = 1//接收到数据帧后
    }
    public class Global
    {
        static public Encoding Encode = System.Text.ASCIIEncoding.Default;
    }

    public class CSerialPort
    {


        private Queue<SerialDebugReceiveData> receiveQueue = new Queue<SerialDebugReceiveData>();
        private List<CSendParam> sendList = new List<CSendParam>();

        private SerialPort _serialPort = new SerialPort();
        private bool IsReceiveStart = false;
        private Thread receiveThread;
        private Thread parseThread;
        private bool IsSendStart = false;
        private Thread sendThread;
        private TimeSpan delayTime = new TimeSpan(10 * 100); // 100us
        private int LoopCount = 0;
        private int _ReceiveTimeOut = 3;
        private bool _SendThreadBusy = false;
        public delegate void ReceivedEventHandler(object sender, SerialDebugReceiveData e);
        public event ReceivedEventHandler ReceivedEvent;

        public delegate void SendCompletedEventHandler(object sender, SendCompletedEventArgs e);
        public event SendCompletedEventHandler SendCompletedEvent;
        public event EventHandler SendOverEvent;

        private AutoResetEvent waitReceiveEvent = new AutoResetEvent(false);
        private ManualResetEvent waitParseEvent = new ManualResetEvent(false);
        private ManualResetEvent uartReceivedEvent = new ManualResetEvent(false);

        public CSerialPort(SerialPort sport)
        {
            _serialPort = sport;
        }

        public SerialPort serialPort
        {
            get { return _serialPort; }
            set { _serialPort = value; }
        }

        public int ReceiveTimeOut
        {
            get { return _ReceiveTimeOut; }
            set { _ReceiveTimeOut = value; }
        }

        public bool SendThreadBusy
        {
            get { return _SendThreadBusy; }
        }


        public void Start()
        {

            try
            {
                IsReceiveStart = true;
                lock (receiveQueue)
                {
                    receiveQueue.Clear();
                }

                lock (sendList)
                {
                    sendList.Clear();
                }

                uartReceivedEvent.Reset();
                waitReceiveEvent.Reset();
                waitParseEvent.Reset();

                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
                serialPort.Open();
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);

                releaseThread(receiveThread);
                releaseThread(sendThread);

                receiveThread = new Thread(new ThreadStart(ReceiveThreadHandler));
                receiveThread.IsBackground = true;
                receiveThread.Name = "receiveThread";
                receiveThread.Start();

                parseThread = new Thread(new ThreadStart(ParseThreadHandler));
                parseThread.IsBackground = true;
                parseThread.Name = "parseThread";
                parseThread.Start();

                Send(sendList, 1);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

        }

        public void Stop()
        {
            try
            {
                IsReceiveStart = false;
                IsSendStart = false;
                if (serialPort != null)
                {

                    lock (serialPort)
                    {
                        serialPort.DataReceived -= new SerialDataReceivedEventHandler(serialPort_DataReceived);
                        if (serialPort.IsOpen)
                        {
                            serialPort.Close();
                        }

                    }
                }
                releaseThread(receiveThread);

            }
            catch (System.Exception ex)
            {
                throw ex;
            }

        }

        public void StopReceive()
        {
            IsReceiveStart = false;
        }

        public void StopSend()
        {
            IsSendStart = false;
            waitParseEvent.Set();
            waitParseEvent.Reset();

            while (SendThreadBusy)
            {
                Thread.Sleep(10);
            }

            //releaseThread(sendThread);
        }
        public void Send(List<CSendParam> list)
        {
            LoopCount = 1;
            Send(list, LoopCount);
        }
        public void Send(CSendParam cSendParam)
        {
            LoopCount = 1;
            Send(new List<CSendParam> { new CSendParam(SendParamFormat.ASCII, SendParamMode.SendAfterLastSend, 0, "OK") }, LoopCount);
        }
        public void Send(List<CSendParam> list, int loop)
        {

            if (sendThread != null)
            {
                if (sendThread.IsAlive)
                {
                    releaseThread(sendThread);
                }
            }


            LoopCount = loop;
            lock (sendList)
            {
                sendList.Clear();
            }
            sendList = list;
            IsSendStart = true;

            sendThread = new Thread(new ThreadStart(SendThreadHandler));
            sendThread.IsBackground = true;
            sendThread.Name = "sendThread";
            sendThread.Start();
        }

        public void Write(byte[] data)
        {
            Write(data, 0, data.Length);
        }
        public void Write(byte[] bytes, int offset, int count)
        {
            if (_serialPort != null && _serialPort.IsOpen)
            {
                lock (_serialPort)
                {
                    _serialPort.Write(bytes, offset, count);
                }
            }
        }

        private bool SerialPortWrite(byte[] bytes, int offset, int count)
        {
            if (_serialPort != null && _serialPort.IsOpen)
            {
                lock (_serialPort)
                {
                    _serialPort.Write(bytes, offset, count);
                    return true;
                }
            }
            return false;
        }

        void releaseThread(Thread th)
        {
            try
            {
                if (th != null)
                {
                    lock (th)
                    {
                        if (th.IsAlive)
                        {
                            th.Abort();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }

        void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (uartReceivedEvent != null)
            {
                uartReceivedEvent.Set();
            }

        }

        /// <summary>
        /// 接收线程
        /// </summary>
        private void ReceiveThreadHandler()
        {

            //byte[] receiveBytes = new byte[4 * 1024];
            while (IsReceiveStart)
            {
                try
                {
                    if (_serialPort.IsOpen)
                    {
                        try
                        {
                            bool IsNeedContinueReceive = false;
                            int dataLen;
                            if (uartReceivedEvent.WaitOne() || IsNeedContinueReceive)
                            {
                                uartReceivedEvent.Reset();

                                //DateTime beginTime = DateTime.Now;
                                int buffSize = 0;
                                do
                                {
                                    buffSize = serialPort.BytesToRead;
                                    if (buffSize >= 4 * 1024)
                                    {
                                        IsNeedContinueReceive = true;
                                        break;
                                    }
                                    Thread.Sleep(ReceiveTimeOut);

                                } while (buffSize != serialPort.BytesToRead);

                                if (buffSize > 0)
                                {
                                    byte[] receiveBytes = new byte[buffSize];
                                    dataLen = serialPort.Read(receiveBytes, 0, receiveBytes.Length);
                                    if (dataLen > 0)
                                    {
                                        byte[] bytes = new byte[dataLen];
                                        Array.Copy(receiveBytes, bytes, dataLen);
                                        lock (receiveQueue)
                                        {
                                            receiveQueue.Enqueue(new SerialDebugReceiveData(bytes));
                                        }
                                        waitReceiveEvent.Set();
                                    }
                                }
                            }

                        }
                        catch (System.Exception ex)
                        {
                            Debug.WriteLine(ex.ToString());
                        }

                    }
                    else
                    {
                        Thread.Sleep(10);
                    }

                }
                catch (System.Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }

            }
        }

        /// <summary>
        /// 接收消息处理线程
        /// </summary>
        private void ParseThreadHandler()
        {
            while (IsReceiveStart)
            {
                try
                {
                    SerialDebugReceiveData data = null;
                    lock (receiveQueue)
                    {
                        if (receiveQueue.Count > 0)
                        {
                            data = receiveQueue.Dequeue();
                        }
                    }

                    if (data != null)
                    {

                        if (ReceivedEvent != null)
                        {
                            ReceivedEvent(this, data);
                        }
                        waitParseEvent.Set();
                    }
                    else
                    {
                        waitReceiveEvent.WaitOne(10);
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine("数据处理线程：" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 发送线程
        /// </summary>
        private void SendThreadHandler()
        {
            bool IsFirstSend = true;

            if (LoopCount == 0)
            {
                LoopCount = int.MaxValue;
            }
            try
            {
                while (LoopCount > 0 && IsSendStart)
                {
                    LoopCount--;

                    waitParseEvent.Reset();

                    int index = 0;
                    while (index < sendList.Count && IsSendStart)
                    {
                        _SendThreadBusy = true;

                        CSendParam sendParam = null;
                        lock (sendList)
                        {
                            sendParam = sendList[index];
                        }
                        index++;

                        if (sendParam != null)
                        {
                            bool DelayEnable = true;
                            if (sendParam.Mode == SendParamMode.SendAfterLastSend)
                            {
                                if (IsFirstSend)
                                {
                                    DelayEnable = false;
                                }
                            }
                            else if (sendParam.Mode == SendParamMode.SendAfterReceived)
                            {
                                waitParseEvent.WaitOne();
                            }
                            IsFirstSend = false;

                            if (DelayEnable && sendParam.DelayTime > 0)
                            {
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                while (ts.TotalMilliseconds < sendParam.DelayTime)
                                {
                                    Thread.Sleep(delayTime);
                                    ts = DateTime.Now - startTime;
                                    if (!IsSendStart)
                                    {
                                        break;
                                    }
                                };
                            }

                            if (IsSendStart && SerialPortWrite(sendParam.DataBytes, 0, sendParam.DataBytes.Length))
                            {
                                if (SendCompletedEvent != null)
                                {
                                    SendCompletedEventHandler handler = SendCompletedEvent;
                                    handler(this, new SendCompletedEventArgs(sendParam));
                                }
                            }
                            else
                            {
                                IsSendStart = false;
                            }

                            waitParseEvent.Reset();
                        }
                        _SendThreadBusy = false;
                    }

                }

            }
            catch (System.Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                if (SendOverEvent != null)
                {
                    SendOverEvent(this, null);
                }
            }


        }
    }


    public class SerialDebugReceiveData : EventArgs
    {
        private readonly DateTime _ReceiveTime;
        private readonly byte[] _ReceiveData;
        private readonly int _DataLen;

        public SerialDebugReceiveData(byte[] data)
        {
            _ReceiveData = data;
            _ReceiveTime = DateTime.Now;
            if (data != null)
            {
                _DataLen = data.Length;
            }
            else
            {
                _DataLen = 0;
            }
        }

        public byte[] ReceiveData
        {
            get { return _ReceiveData; }
        }

        public DateTime ReceiveTime
        {
            get { return _ReceiveTime; }
        }

        public int DataLen
        {
            get { return _DataLen; }
        }

        public string TimeString
        {
            get
            {
                return string.Format("[{0}.{1:D3}]", _ReceiveTime.ToString("yyyy-MM-dd HH:mm:ss"), _ReceiveTime.Millisecond);
            }
        }

        public string HexString
        {
            get
            {
                return string.Format("{0} ", BitConverter.ToString(_ReceiveData).Replace('-', ' '));
            }
        }

        public string ASCIIString
        {
            get
            {
                return StreamConverter.ArrayToAsciiString(Global.Encode, _ReceiveData);
            }
        }

        public string DecString
        {
            get
            {
                StringBuilder sb = new StringBuilder();

                foreach (byte b in _ReceiveData)
                {
                    sb.AppendFormat("{0} ", Convert.ToInt32(b));
                }

                return sb.ToString();
            }

        }
    }

    public class SendCompletedEventArgs : EventArgs
    {
        private readonly DateTime _SendTime;
        private CSendParam _SendParam;

        public SendCompletedEventArgs(CSendParam sendParam)
        {
            _SendTime = DateTime.Now;
            _SendParam = sendParam;

            //if (sendParam!=null)
            //{
            //    _SendParam = new CSendParam(sendParam.Format,
            //    sendParam.Mode,
            //    sendParam.DelayTime,
            //    sendParam.DataBytes, 0, sendParam.DataLen);
            //}
            //else
            //{
            //    _SendParam = null;
            //}
        }

        public DateTime SendTime
        {
            get { return _SendTime; }
        }

        public CSendParam SendParam
        {
            get { return _SendParam; }
        }

        public string TimeString
        {
            get
            {
                return string.Format("[{0}.{1:D3}]", _SendTime.ToString("yyyy-MM-dd HH:mm:ss"), _SendTime.Millisecond);
            }
        }
    }
    public class StreamConverter
    {


        #region Array<--->AsciiString
        /// <summary>
        /// 字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public byte[] AsciiStringToArray(Encoding encoding, string value, int startIndex, int length)
        {
            try
            {
                //Encoding code = System.Text.Encoding.GetEncoding("UTF-8");
                return encoding.GetBytes(value.Substring(startIndex, length));

                //return System.Text.ASCIIEncoding.Default.GetBytes(value.Substring(startIndex, length));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public byte[] AsciiStringToArray(Encoding encoding, string value)
        {
            return AsciiStringToArray(encoding, value, 0, value.Length);
        }

        /// <summary>
        /// 数组转字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public string ArrayToAsciiString(Encoding encoding, byte[] value, int startIndex, int length)
        {
            try
            {
                //Encoding code = System.Text.Encoding.GetEncoding("UTF-8");
                return encoding.GetString(value, startIndex, length);
                //return System.Text.ASCIIEncoding.Default.GetString(value, startIndex, length);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 数组转字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public string ArrayToAsciiString(Encoding encoding, byte[] value)
        {
            if (value != null)
                return ArrayToAsciiString(encoding, value, 0, value.Length);
            else
                return string.Empty;
        }
        #endregion

        #region Array<-->BinaryString

        /// <summary>
        /// 二进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public byte[] BinaryStringToArray(string value, int startIndex, int length)
        {
            try
            {
                List<byte> list = new List<byte>();
                string binString = value.Substring(startIndex, length).Replace(" ", "");
                int i;
                for (i = 0; i < binString.Length; i += 8)
                {
                    int len = 8;
                    if (i + 8 <= binString.Length)
                    {
                        len = 8;
                    }
                    else
                    {
                        len = binString.Length - i;
                    }
                    byte b = Convert.ToByte(binString.Substring(i, len), 2);
                    list.Add(b);
                }

                return list.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 二进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public byte[] BinaryStringToArray(string value)
        {
            return BinaryStringToArray(value, 0, value.Length);
        }

        /// <summary>
        /// 字节数组转二进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public string ArrayToBinaryString(byte[] value, int startIndex, int length)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < length; i++)
                {
                    byte b = value[startIndex + i];
                    string s = Convert.ToString(b, 2).PadLeft(8, '0');
                    sb.Append(s);
                    sb.Append(" ");
                }
                return sb.ToString().Trim();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 字节数组转二进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public string ArrayToBinaryString(byte[] value)
        {
            if (value != null)
                return ArrayToBinaryString(value, 0, value.Length);
            else
                return string.Empty;
        }

        #endregion

        #region Array<-->OctalString

        /// <summary>
        /// 八进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public byte[] OctalStringToArray(string value, int startIndex, int length)
        {
            try
            {
                List<byte> list = new List<byte>();
                string[] strArray = value.Substring(startIndex, length).Split(new char[] { ',', ' ', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in strArray)
                {
                    byte b = Convert.ToByte(Convert.ToInt32(s, 8) & 0xFF);
                    list.Add(b);
                }
                return list.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 八进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public byte[] OctalStringToArray(string value)
        {
            return OctalStringToArray(value, 0, value.Length);
        }

        /// <summary>
        /// 字节数组转八进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public string ArrayToOctalString(byte[] value, int startIndex, int length)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < length; i++)
                {
                    int b = value[startIndex + i];
                    sb.AppendFormat("{0} ", Convert.ToString(b, 8));
                }
                return sb.ToString().Trim();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 字节数组转八进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public string ArrayToOctalString(byte[] value)
        {
            if (value != null)
                return ArrayToOctalString(value, 0, value.Length);
            else
                return string.Empty;
        }

        #endregion

        #region Array<-->DecimalString

        /// <summary>
        /// 十进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public byte[] DecimalStringToArray(string value, int startIndex, int length)
        {
            try
            {
                List<byte> list = new List<byte>();
                string[] strArray = value.Substring(startIndex, length).Split(new char[] { ' ', ',', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in strArray)
                {
                    byte b = Convert.ToByte(Convert.ToInt32(s, 10) & 0xFF);
                    list.Add(b);
                }

                return list.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 十进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public byte[] DecimalStringToArray(string value)
        {
            return DecimalStringToArray(value, 0, value.Length);
        }

        /// <summary>
        /// 数组转十进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public string ArrayToDecimalString(byte[] value, int startIndex, int length)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < length; i++)
                {
                    int b = value[startIndex + i];
                    sb.AppendFormat("{0} ", Convert.ToString(b, 10));
                }
                return sb.ToString().Trim();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 数组转十进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public string ArrayToDecimalString(byte[] value)
        {
            if (value != null)
                return ArrayToDecimalString(value, 0, value.Length);
            else
                return string.Empty;
        }

        #endregion

        #region Array<-->HexString

        /// <summary>
        /// 十进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public byte[] HexStringToArray(string value, int startIndex, int length)
        {
            try
            {
                List<byte> list = new List<byte>();
                string inputText = Regex.Replace(value.Substring(startIndex, length), @"[0-9A-Fa-f]{2}", "$0 ");
                string[] strArray = inputText.Split(new string[] { ",", " ", "0x", ",0X", "，", "(", ")", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in strArray)
                {
                    list.Add(Convert.ToByte(s, 16));
                }
                return list.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 十进制字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public byte[] HexStringToArray(string value)
        {
            return HexStringToArray(value, 0, value.Length);
        }

        /// <summary>
        /// 数组转十六进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public string ArrayToHexString(byte[] value, int startIndex, int length)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < length; i++)
                {
                    int b = value[startIndex + i];
                    sb.AppendFormat("{0:X2} ", b);
                }
                return sb.ToString().Trim();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 数组转十进制字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public string ArrayToHexString(byte[] value)
        {
            if (value != null)
                return ArrayToHexString(value, 0, value.Length);
            else
                return string.Empty;
        }


        #endregion

        #region Text<-->HexString
        static public string TextToHexString(string text)
        {
            byte[] bytes = Encoding.Default.GetBytes(text);
            return BitConverter.ToString(bytes).Replace("-", "");
        }

        static public string HexStringToText(string hexStr)
        {
            byte[] bytes = HexStringToArray(hexStr);
            return Encoding.Default.GetString(bytes);
        }

        #endregion

        #region Array<-->Base64
        /// <summary>
        /// Base64字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public byte[] Base64StringToArray(string value, int startIndex, int length)
        {
            try
            {
                return Convert.FromBase64String(value.Substring(startIndex, length));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Base64字符串转字节数组
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public byte[] Base64StringToArray(string value)
        {
            return Base64StringToArray(value, 0, value.Length);
        }

        /// <summary>
        /// 数组转Base64字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <param name="startIndex">数组起始位置</param>
        /// <param name="length">要转换的长度</param>
        /// <returns></returns>
        static public string ArrayToBase64String(byte[] value, int startIndex, int length)
        {
            try
            {
                return Convert.ToBase64String(value, startIndex, length, Base64FormattingOptions.None);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 数组转字符串
        /// </summary>
        /// <param name="value">要转换的数组</param>
        /// <returns></returns>
        static public string ArrayToBase64String(byte[] value)
        {
            if (value != null)
                return ArrayToBase64String(value, 0, value.Length);
            else
                return string.Empty;
        }
        #endregion

        #region Array-->String

        static private string _ArrayToString<T>(T[] value, int startIndex, int length, int toBase)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < length; i++)
                {
                    T b = value[startIndex + i];
                    sb.AppendFormat("{0} ", Convert.ToString(Convert.ToInt32(b), toBase));
                }
                return sb.ToString().Trim();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        static public string ArrayToString(int[] value, int startIndex, int length, int toBase)
        {
            return _ArrayToString(value, startIndex, length, toBase);
        }
        static public string ArrayToString(int[] value, int startIndex, int length)
        {
            return ArrayToString(value, startIndex, length, 16);
        }
        static public string ArrayToString(int[] value, int toBase)
        {
            if (value != null)
            {
                return ArrayToString(value, 0, value.Length, toBase);
            }
            else
            {
                return "";
            }
        }
        static public string ArrayToString(int[] value)
        {
            return ArrayToString(value, 16);
        }


        static public string ArrayToString(byte[] value, int startIndex, int length, int toBase)
        {
            return _ArrayToString(value, startIndex, length, toBase);
        }
        static public string ArrayToString(byte[] value, int startIndex, int length)
        {
            return ArrayToString(value, startIndex, length, 16);
        }
        static public string ArrayToString(byte[] value, int toBase)
        {
            if (value != null)
            {
                return ArrayToString(value, 0, value.Length, toBase);
            }
            else
            {
                return "";
            }
        }

        static public string ArrayToString(byte[] value)
        {
            return ArrayToString(value, 16);
        }
        #endregion
    }

}
